import {Request,Response,NextFunction} from 'express'
import * as userService from '../user/user.service'
import bcrypt from 'bcrypt'
import {TokenPayload} from './auth.interface'
import jwt from 'jsonwebtoken'
import { TOKEN_KEY } from '../app/app.config'

export const validataLoginData=async(request:Request,response:Response,next:NextFunction)=>{
    console.log('验证用户登录数据')
    const {name,password} = request.body
    if(!name) return next(new Error('NAME_IS_REQUIRE'))
    if(!password) return next(new Error('PASSWORD_IS_REQUIRED')) 

    const user = await userService.getUserByName(name,{password:true})
    console.log(user)
    if(!user) return next(new Error('USER_DOES_NOT_EXIST'))

    const matched = await bcrypt.compare(password,user.password)
    
    console.log(matched)
    if(!matched) return next(new Error('PASSWORD_DOSE_NOT_MATCH'))

    request.body.user=user;
    next()
}

export const currentUser=(request:Request,response:Response,next:NextFunction)=>{
    let user:TokenPayload = {
        id:null,
        // 游客
        name:'anonymous'
    }
    try {
        const authorizaton = request.header('Authorization')

        // 提取jwt令牌
        const token = authorizaton
        
        if(token){
            const decode=jwt.verify(token,TOKEN_KEY)
            // console.log(decode,'///')
            // { id: 26, name: 'root', iat: 1646743104 } iat:token 生成的唯一值

            user=decode as TokenPayload
        }
    } catch (error) {
        next(error)
    }
    request.user=user
    next()
}

export const authGuard=async(request:Request,response:Response,next:NextFunction)=>{
    if(request.user.id){
        next()
    }
    else{
        next(new Error('UNAUTHORIZED'))
    }
}